<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'

// 基础表单控制
const baseForm = reactive({
  name: '',
  region: '',
  date: '',
  delivery: false,
  type: [],
  resource: '',
  desc: ''
})

const baseFormRef = ref(null)
const baseFormRules = {
  name: [
    { required: true, message: '请输入活动名称', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  region: [
    { required: true, message: '请选择活动区域', trigger: 'change' }
  ],
  date: [
    { required: true, message: '请选择日期', trigger: 'change' }
  ],
  type: [
    { type: 'array', required: true, message: '请至少选择一个活动类型', trigger: 'change' }
  ],
  resource: [
    { required: true, message: '请选择资源', trigger: 'change' }
  ],
  desc: [
    { required: true, message: '请填写活动描述', trigger: 'blur' }
  ]
}

const submitBaseForm = async () => {
  if (!baseFormRef.value) return
  
  await baseFormRef.value.validate((valid, fields) => {
    if (valid) {
      ElMessage.success('表单验证成功')
    } else {
      console.log('验证失败', fields)
      ElMessage.error('表单验证失败，请检查输入')
    }
  })
}

const resetBaseForm = () => {
  baseFormRef.value?.resetFields()
}

// 自定义校验表单
const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (customForm.checkPass !== '') {
      customFormRef.value.validateField('checkPass')
    }
    callback()
  }
}

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== customForm.pass) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const validateAge = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('请输入年龄'))
  }
  if (!Number.isInteger(value)) {
    callback(new Error('请输入数字值'))
  } else {
    if (value < 18) {
      callback(new Error('年龄必须大于等于18岁'))
    } else {
      callback()
    }
  }
}

const customForm = reactive({
  pass: '',
  checkPass: '',
  age: '',
  email: '',
  phone: ''
})

const customFormRef = ref(null)
const customFormRules = {
  pass: [{ validator: validatePass, trigger: 'blur' }],
  checkPass: [{ validator: validatePass2, trigger: 'blur' }],
  age: [{ validator: validateAge, trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

const submitCustomForm = async () => {
  if (!customFormRef.value) return
  
  await customFormRef.value.validate((valid, fields) => {
    if (valid) {
      ElMessage.success('表单验证成功')
    } else {
      console.log('验证失败', fields)
      ElMessage.error('表单验证失败，请检查输入')
    }
  })
}

const resetCustomForm = () => {
  customFormRef.value?.resetFields()
}

// 动态表单项
const dynamicForm = reactive({
  domains: [{
    key: 1,
    value: ''
  }],
  email: ''
})

const dynamicFormRef = ref(null)
const dynamicFormRules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  domains: {
    type: 'array',
    required: true,
    defaultField: {
      type: 'object',
      fields: {
        value: {
          type: 'string',
          required: true,
          message: '域名不能为空'
        }
      }
    }
  }
}

const removeDomain = (item) => {
  const index = dynamicForm.domains.indexOf(item)
  if (index !== -1) {
    dynamicForm.domains.splice(index, 1)
  }
}

const addDomain = () => {
  dynamicForm.domains.push({
    key: Date.now(),
    value: ''
  })
}

const submitDynamicForm = async () => {
  if (!dynamicFormRef.value) return
  
  await dynamicFormRef.value.validate((valid, fields) => {
    if (valid) {
      ElMessage.success('表单验证成功')
    } else {
      console.log('验证失败', fields)
      ElMessage.error('表单验证失败，请检查输入')
    }
  })
}

const resetDynamicForm = () => {
  dynamicFormRef.value?.resetFields()
}
</script>

<template>
  <div class="common-layout">
    <el-container>
      <el-main>
        <!-- 基础表单 -->
        <el-card class="box-card mb-20">
          <template #header>
            <div class="card-header">
              <span>基础表单</span>
            </div>
          </template>

          <div class="form-description">
            <p>基础表单包含各种输入控件，适用于简单的数据录入</p>
          </div>

          <el-form
            ref="basicFormRef"
            :model="basicForm"
            :rules="basicRules"
            label-width="120px"
            class="demo-form"
          >
            <el-form-item label="用户名" prop="username">
              <el-input v-model="basicForm.username" placeholder="请输入用户名" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="basicForm.password" type="password" placeholder="请输入密码" show-password />
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input v-model="basicForm.confirmPassword" type="password" placeholder="请再次输入密码" show-password />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="basicForm.email" placeholder="请输入邮箱" />
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="basicForm.phone" placeholder="请输入手机号" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitBasicForm(basicFormRef)">提交</el-button>
              <el-button @click="resetBasicForm(basicFormRef)">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 内联表单 -->
        <el-card class="box-card mb-20">
          <template #header>
            <div class="card-header">
              <span>内联表单</span>
            </div>
          </template>

          <div class="form-description">
            <p>内联表单适用于简单的搜索条件等场景</p>
          </div>

          <el-form :inline="true" :model="inlineForm" class="demo-form-inline">
            <el-form-item label="审批人">
              <el-input v-model="inlineForm.user" placeholder="审批人" />
            </el-form-item>
            <el-form-item label="活动区域">
              <el-select v-model="inlineForm.region" placeholder="活动区域">
                <el-option label="区域一" value="shanghai" />
                <el-option label="区域二" value="beijing" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onInlineFormSubmit">查询</el-button>
              <el-button @click="resetInlineForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 复杂表单 -->
        <el-card class="box-card mb-20">
          <template #header>
            <div class="card-header">
              <span>复杂表单</span>
            </div>
          </template>

          <div class="form-description">
            <p>复杂表单包含多种高级控件，适用于复杂数据的录入</p>
          </div>

          <el-form
            ref="advancedFormRef"
            :model="advancedForm"
            :rules="advancedRules"
            label-width="120px"
            class="demo-form"
          >
            <el-form-item label="活动名称" prop="name">
              <el-input v-model="advancedForm.name" />
            </el-form-item>
            <el-form-item label="活动区域" prop="region">
              <el-select v-model="advancedForm.region" placeholder="请选择活动区域">
                <el-option label="区域一" value="shanghai" />
                <el-option label="区域二" value="beijing" />
              </el-select>
            </el-form-item>
            <el-form-item label="活动时间" required>
              <el-col :span="11">
                <el-form-item prop="date1">
                  <el-date-picker
                    v-model="advancedForm.date1"
                    type="date"
                    placeholder="选择日期"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="2" class="text-center">
                <span class="text-gray-500">-</span>
              </el-col>
              <el-col :span="11">
                <el-form-item prop="date2">
                  <el-time-picker
                    v-model="advancedForm.date2"
                    placeholder="选择时间"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-form-item>
            <el-form-item label="即时配送" prop="delivery">
              <el-switch v-model="advancedForm.delivery" />
            </el-form-item>
            <el-form-item label="活动性质" prop="type">
              <el-checkbox-group v-model="advancedForm.type">
                <el-checkbox label="美食/餐厅线上活动" name="type" />
                <el-checkbox label="地推活动" name="type" />
                <el-checkbox label="线下主题活动" name="type" />
                <el-checkbox label="单纯品牌曝光" name="type" />
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="特殊资源" prop="resource">
              <el-radio-group v-model="advancedForm.resource">
                <el-radio label="线上品牌商赞助" />
                <el-radio label="线下场地免费" />
              </el-radio-group>
            </el-form-item>
            <el-form-item label="活动形式" prop="desc">
              <el-input v-model="advancedForm.desc" type="textarea" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitAdvancedForm(advancedFormRef)">创建</el-button>
              <el-button @click="resetAdvancedForm(advancedFormRef)">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 动态表单 -->
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>动态表单</span>
            </div>
          </template>

          <div class="form-description">
            <p>动态表单可以根据需要添加或删除表单项，适用于动态数据录入</p>
          </div>

          <el-form
            ref="dynamicFormRef"
            :model="dynamicForm"
            :rules="dynamicRules"
            label-width="120px"
            class="demo-dynamic-form"
          >
            <el-form-item label="活动名称" prop="activityName">
              <el-input v-model="dynamicForm.activityName" />
            </el-form-item>
            
            <el-divider content-position="center">参与人员信息</el-divider>
            
            <el-form-item
              v-for="(domain, index) in dynamicForm.domains"
              :key="domain.key"
              :label="'参与人 ' + (index + 1)"
              :prop="'domains.' + index + '.value'"
              :rules="{
                required: true,
                message: '参与人信息不能为空',
                trigger: 'blur'
              }"
            >
              <div class="domain-item">
                <el-input v-model="domain.value" />
                <el-button
                  type="danger"
                  @click.prevent="removeDomain(domain)"
                  :disabled="dynamicForm.domains.length <= 1"
                >
                  删除
                </el-button>
              </div>
            </el-form-item>
            
            <el-form-item>
              <el-button @click="addDomain">添加参与人</el-button>
              <el-button type="primary" @click="submitDynamicForm(dynamicFormRef)">提交</el-button>
              <el-button @click="resetDynamicForm(dynamicFormRef)">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-main>
    </el-container>
  </div>
</template>

<style scoped>
.mb-20 {
  margin-bottom: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.form-description {
  margin-bottom: 20px;
  color: #666;
}
.text-center {
  text-align: center;
}
.domain-item {
  display: flex;
  align-items: center;
  gap: 10px;
}
.demo-form {
  max-width: 600px;
}
</style> 